<template>
  <div class="prescription-page">
    <!-- 新增按钮 -->
    <div class="button-group">
      <el-button type="primary" :disabled="isPaid" @click="charge">
        {{ isPaid ? "已收费" : "收费" }}
      </el-button>
      <el-button type="success" :disabled="!isPaid" @click="dispense"
        >发药</el-button
      >
    </div>
    <!-- 显示已保存的处方 -->
    <div class="saved-prescriptions">
      <!-- 新增一个容器用于纵向滚动 -->
      <div class="saved-prescriptions-scroll">
        <div
          v-for="(savedItem, index) in savedPrescriptions"
          :key="index"
          class="saved-prescription-item"
        >
          <el-form :model="savedItem" :inline="true" label-width="60px">
            <el-form-item label="药品编码">
              <el-input v-model="savedItem.code" readonly style="width: 80px" />
            </el-form-item>
            <el-form-item label="药品名称">
              <el-input v-model="savedItem.name" readonly />
            </el-form-item>
            <el-form-item label="单价">
              <el-input v-model="savedItem.price" readonly />
            </el-form-item>
            <el-form-item label="数量">
              <el-input v-model="savedItem.count" readonly />
            </el-form-item>
            <el-form-item label="用法">
              <el-input v-model="savedItem.useage" readonly />
            </el-form-item>
            <el-form-item label="总价">
              <el-input v-model="savedItem.totalprice" readonly />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="savedItem.beizhu" readonly />
            </el-form-item>
          </el-form>
        </div>
        <!-- 当数据为空时显示此部分 -->
        <div v-if="savedPrescriptions.length === 0" class="no-data-placeholder">
          <i
            class="el-icon - circle - close"
            style="
              font-size: 60px;
              color: #ccc;
              display: block;
              margin: 0 auto 20px;
            "
          ></i>
          <p style="text-align: center; color: #666">暂无待发药品信息</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import {
  getUnsentPrescriptions,
  updatePaymentStatus,
  cardpay,
} from "@/api/prescription/prescription";
import { dispenseMedicines } from "@/api/drug/stock";
import { ElMessage, ElMessageBox } from "element-plus";
import { number } from "echarts";
import { pa } from "element-plus/es/locales.mjs";

const props = defineProps({
  clinicId: String,
  patientId: number,
});

const savedPrescriptions = ref([]);
const isPaid = ref(false);
const totalAmount = ref(0);

// 加载已保存的处方
const loadSavedPrescriptions = async () => {
  try {
    const response = await getUnsentPrescriptions({ clinicId: props.clinicId });
    savedPrescriptions.value = response.rows || [];
    totalAmount.value = savedPrescriptions.value.reduce(
      (acc, item) => acc + parseFloat(item.totalprice),
      0
    );
    // 明确根据 ispay 的值来设置 isPaid
    if (savedPrescriptions.value.length > 0) {
      isPaid.value = parseInt(savedPrescriptions.value[0].ispay, 10) === 1;
    } else {
      isPaid.value = false;
    }
  } catch (error) {
    console.error("Failed to load saved prescriptions:", error);
    ElMessage.error("加载已保存处方失败");
  }
};

// 收费按钮点击逻辑
const charge = () => {
  ElMessageBox.confirm(
    `请选择支付方式，本次需支付金额：${totalAmount.value} 元`,
    "支付方式",
    {
      confirmButtonText: "现金支付",
      cancelButtonText: "卡余额支付",
      type: "question",
    }
  )
    .then((action) => {
      if (action === "confirm") {
        handlePayment("现金支付");
      } else if (action === "cancel") {
        handlePayment("卡余额支付");
      }
    })
    .catch(() => {
      // 用户取消确认框
    });
};

// 处理支付逻辑
// 处理支付逻辑
const handlePayment = (paymentMethod) => {
  if (paymentMethod === "卡余额支付") {
    // 调用后端接口扣除卡余额
    deductBalance({
      patientId: props.patientId,
      paymentMethod: paymentMethod,
    })
      .then(() => {
        isPaid.value = true;
        ElMessage.success("卡余额支付成功");
      });
      handleCashPayment();
  } else if (paymentMethod === "现金支付") {
    // 处理现金支付逻辑
    handleCashPayment();
  }
};

// 调用后端接口扣除卡余额
const deductBalance = (params) => {
  return cardpay(params);
};

// 处理支付逻辑
const handleCashPayment = () => {
  updatePaymentStatus({ clinicId: props.clinicId, ispay: 1 })
    .then(() => {
      isPaid.value = true;
      ElMessage.success("支付成功");
    })
    .catch((error) => {
      console.error("更新收费状态接口调用失败:", error);
      ElMessage.error("支付失败，请重试");
    });
};

// 发药按钮点击逻辑
const dispense = () => {
  ElMessageBox.confirm("是否确定发药？", "确认发药", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then((action) => {
      if (action === "confirm") {
        // 准备要发药的药品信息
        const medicinesToDispense = savedPrescriptions.value.map((item) => ({
          clinicId: props.clinicId,  
          code: item.code,
          name: item.name,
          count: parseInt(item.count, 10),
        }));
        console.log("medicinesToDispense:", medicinesToDispense);
        // 直接传递药品对象数组
        dispenseMedicines(medicinesToDispense)
          .then(() => {
            ElMessage.success("发药成功，库存已扣除");
          })
          .catch((error) => {
            console.error("发药失败:", error);
            ElMessage.error("发药失败，请重试");
          });
      }
    })
    .catch(() => {
      // 用户取消确认框
    });
};

// 监听 props 的变化
watch(
  () => props.clinicId,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      loadSavedPrescriptions();
    }
  }
);

// 在组件加载时调用
onMounted(() => {
  loadSavedPrescriptions();
});
</script>

<style scoped>
.prescription-page {
  padding: 20px;
}

.prescription-list {
  margin-bottom: 20px;
}

.prescription-item {
  margin-bottom: 10px;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
}

.saved-prescriptions {
  margin-top: 20px;
}

/* 新增纵向滚动容器样式 */
.saved-prescriptions-scroll {
  max-height: 200px; /* 设置固定高度，可根据需要调整 */
  overflow-y: auto; /* 添加纵向滚动条 */
}

.saved-prescription-item {
  margin-bottom: 10px;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 4px;
  display: flex;
  flex-wrap: nowrap; /* 让字段在同一行显示 */
  overflow-x: auto; /* 添加横向滚动条 */
  white-space: nowrap; /* 防止内容换行 */
}

/* 已保存处方表单项样式 */
.saved-prescription-item.el-form-item {
  margin-bottom: 0;
  margin-right: 5px;
}

.beizhu-wide {
  width: 250px;
}

/* 分隔线样式 */
.separator {
  height: 4px;
  background-color: #999;
  margin: 30px 0;
  border-radius: 2px;
}

/* 无数据占位样式 */
.no-data-placeholder {
  padding: 50px 0;
}

/* 按钮组样式 */
.button-group {
  margin-bottom: 20px;
}
</style>
